package com.haiertvbic.tvnow;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haiertvbic.tvnow.baseactivity.SwitchActivity;
import com.haiertvbic.tvnow.db.DbAdapter;
import com.haiertvbic.tvnow.model.ProgramDetail;
import com.haiertvbic.tvnow.model.ProgramItem;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.network.ImageUtil;
import com.haiertvbic.tvnow.network.NetUtil;
import com.haiertvbic.tvnow.testblock.Function;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.TimeUtil;

public class ProgramListActivity extends SwitchActivity {
	private Activity context = ProgramListActivity.this;
	private String TAG = "ProgramListActivity";

	private ListView programs;
	private TextView loading;
	private ProgressBar loadingBar;

	private int channelId;
	private String channelName;

	private ArrayList<ProgramDetail> programList;
	private boolean isOutTme;

	// 能否到跨频道搜索列表
	private int position;
	private static String DSJ = "电视剧";
	private String itemType;
	// 取节目
	private Thread programThread;
	private Handler mhandler;

	private ProgramAdapter adapter;
	// 节目海报的缓存
	HashMap<String, SoftReference<Bitmap>> posterCache = new HashMap<String, SoftReference<Bitmap>>();

	@Override
	public void findView() {
		getChannelData();

		setContentView(R.layout.activity2_common_list);
		TextView channelNameTV = (TextView) findViewById(R.id.pro_name);
		channelNameTV.setText(channelName);

		TextView screenPoint = (TextView) findViewById(R.id.screen_point);
		String screen = getString(R.string.channel_program);
		screenPoint.setText(screen);

		ImageView screenGuide = (ImageView) findViewById(R.id.screen_point_iv);
		if (Function.function.get("OttInfor")) {
			screenGuide.setImageResource(R.drawable.ott_screen_guide_2);
		} else {
			screenGuide.setImageResource(R.drawable.screen_guide_2);
		}

		loading = (TextView) findViewById(R.id.loading_tv);
		loadingBar = (ProgressBar) findViewById(R.id.bar_on_cha);
		loadingBar.setVisibility(View.GONE);
		programs = (ListView) findViewById(R.id.common_lv);
		programs.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int arg1, long id) {
				position = arg1;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	private void getChannelData() {
		Intent intent = getIntent();
		channelId = intent.getIntExtra("CHA_ID", -1);
		channelName = intent.getStringExtra("CHA_NAME");
		if (Function.testData.get("programlist")) {
			channelId = 46;
			channelName = "湖南卫士";
		}
		Constant.CHANNELID = channelId;
		SLog.d(TAG, "第一屏传来的频道id是：" + channelId + "频道名字" + channelName);
	}

	@Override
	public void setDataSetup() {

		if (programThread != null) {
			programThread = null;
		}
		programThread = new Thread(new Runnable() {

			@Override
			public void run() {
				DbAdapter dbdata = new DbAdapter();
				dbdata.getInstance(context);
				makeItemTypeValue(dbdata);
				programList = dbdata.findProgramById(channelId + "");
				if (!hasProgram()) {
					if (NetUtil.getNetworkInfo(context)) {
						// 没节目
						try {
							programList = EPGWeb.getProgramList(context,
									channelId + "");
							int netCount = programList != null ? programList
									.size() : 0;
							if (netCount < 1) {
								mhandler.sendEmptyMessage(EPGWeb.SERVER_NO_DATA);
							} else {
								programList = EPGWeb.filterByAttribute(
										programList, context);
								if (netCount > 0 && programList.size() == 0) {
									mhandler.sendEmptyMessage(EPGWeb.SERVER_PTYPE_NOT_SUITABLE);
								}
							}
							if (programList != null && programList.size() > 0) {
								netCount = programList.size();
								programList = TimeUtil
										.filterByTime(programList);
								if (netCount > 0 && programList.size() == 0) {
									mhandler.sendEmptyMessage(EPGWeb.SYS_TIME_ERROR);
								} else {
									mhandler.sendEmptyMessage(EPGWeb.DATA_SUC);
								}
								try {
									dbdata.addPrograms(programList);
								} catch (Exception e) {
									// 存储不成功,内存不够
									mhandler.sendEmptyMessage(EPGWeb.STORAGE_LOW);
									SLog.d(TAG, "====" + e.toString());
								}
							}
						} catch (ClientProtocolException e) {
							mhandler.sendEmptyMessage(EPGWeb.SERVER_REQUEST_OUTIME);
							e.printStackTrace();
						} catch (IOException e) {
							mhandler.sendEmptyMessage(EPGWeb.SERVER_REQUEST_OUTIME);
							e.printStackTrace();
						}
					} else {
						mhandler.sendEmptyMessage(EPGWeb.NO_NETWORK);
					}
				} else {
					mhandler.sendEmptyMessage(EPGWeb.DATA_SUC);
				}

			}

			private void makeItemTypeValue(DbAdapter dbdata) {
				ArrayList<ProgramItem> items = dbdata.findFathertItem();
				if (items != null && items.size() > 0) {
				} else {
					items = EPGWeb.getItems(context);
				}
				for (int j = 0; items != null && j < items.size(); j++) {
					String itemTemp = items.get(j).getName();
					if (DSJ.equals(itemTemp)) {
						itemType = items.get(j).getNode();
						break;
					}
				}
			}
		});
		programThread.start();
		if (mhandler != null) {
			return;
		}
		mhandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				loadingBar.setVisibility(View.GONE);
				switch (msg.what) {
				case EPGWeb.DATA_SUC:
					programs.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
					adapter = new ProgramAdapter(context, programList, programs);
					programs.setAdapter(adapter);
					break;
				case EPGWeb.SERVER_NO_DATA:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.server_no_data);
					break;
				case EPGWeb.SERVER_PTYPE_NOT_SUITABLE:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.ptype_error);
					break;
				case EPGWeb.SYS_TIME_ERROR:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.sys_time_error);
					break;
				case EPGWeb.STORAGE_LOW:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.storage_low);
					break;
				case EPGWeb.SERVER_REQUEST_OUTIME:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					String again = getString(R.string.server_request_outime);
					loading.setText(again);
					isOutTme = true;
					break;
				case EPGWeb.NO_NETWORK:
					programs.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.NOnetwork);
					break;

				default:
					break;
				}
			}
		};

	}

	class ProgramAdapter extends BaseAdapter {
		PosterAsyncTask posterAsync;
		HashMap<String, PosterAsyncTask> posterTask = new HashMap<String, PosterAsyncTask>();

		private Context context;
		private ArrayList<ProgramDetail> programList;
		private ListView programs;

		public ProgramAdapter(Activity context,
				ArrayList<ProgramDetail> programList, ListView programs) {
			this.context = context;
			this.programList = programList;
			this.programs = programs;

		}

		@Override
		public int getCount() {

			return programList.size();
		}

		@Override
		public Object getItem(int position) {
			return programList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		class ViewHodler {
			// 节目的开始时间
			TextView startTime;
			// 节目图片
			ImageView poster;
			// 节目的名字
			TextView programName;

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHodler hodler = new ViewHodler();
			if (convertView == null) {
				convertView = View.inflate(context,
						R.layout.layout_program_item, null);
				hodler.startTime = (TextView) convertView
						.findViewById(R.id.detail_stime_tv);
				hodler.poster = (ImageView) convertView
						.findViewById(R.id.detail_iv);
				hodler.programName = (TextView) convertView
						.findViewById(R.id.detail_pro_tv);
				convertView.setTag(hodler);
			} else {
				hodler = (ViewHodler) convertView.getTag();
			}
			ProgramDetail program = programList.get(position);
			String startTemp = null;
			if (TimeUtil.isTomorrowWeek(program)) {
				String tomorrow = context.getResources().getString(
						R.string.tomorrow);
				startTemp = tomorrow + program.getPstime() + "c";
			} else {
				startTemp = program.getPstime() + "c";
			}
			startTemp = "    " + startTemp.replace(":00c", "");
			hodler.startTime.setText(startTemp);
			String nameTemp = "    " + program.getPn();// 四个空格
			hodler.programName.setText(nameTemp);
			String posterUrl;
			posterUrl = program.getPicurl();
			if (posterUrl != null && posterUrl.trim().length() > 0) {
				if (posterCache.containsKey(posterUrl)
						&& posterCache.get(posterUrl).get() != null) {
					Bitmap posterBit = posterCache.get(posterUrl).get();
					hodler.poster.setImageBitmap(posterBit);
					hodler.poster.setVisibility(View.VISIBLE);
				} else {
					synchronized (posterTask) {
						if (posterTask.containsKey(posterUrl)
								&& posterTask.get(posterUrl).isCancelled()) {
							posterAsync = posterTask.get(posterUrl);
							posterAsync.cancel(true);
							posterAsync = null;
						} else {
							posterAsync = new PosterAsyncTask();
							posterTask.put(posterUrl, posterAsync);
						}
						posterAsync.execute(posterUrl);
					}
				}
			} else {
				hodler.poster.setVisibility(View.GONE);
			}

			return convertView;
		}

		class PosterAsyncTask extends AsyncTask<String, Void, Void> {

			private Bitmap posterBit;

			@Override
			protected Void doInBackground(String... params) {
				String posterUrl = params[0];
				posterBit = null;
				posterBit = ImageUtil.getPicData(posterUrl);
				posterCache
						.put(posterUrl, new SoftReference<Bitmap>(posterBit));
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if (posterBit != null && adapter != null) {
					int lastShow = programs.getSelectedItemPosition();
					programs.setAdapter(adapter);
					programs.setSelection(lastShow);
					// programs.requestFocus();
					notifyDataSetChanged();
				}
				super.onPostExecute(result);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		case KeyEvent.KEYCODE_DPAD_LEFT:
			Intent intent = new Intent();
			intent.setClass(context, TVNOWMainActivity.class);
			startActivity(intent);
			break;
		case KeyEvent.KEYCODE_ENTER:
			if (isOutTme) {
				loadingBar.setVisibility(View.VISIBLE);
				loading.setVisibility(View.GONE);
				setDataSetup();
			}
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if (hasProgram()
					&& programList.get(position) != null
					&& !programList.get(position).getPn()
							.equalsIgnoreCase("最后一项")) {
				if (filterDSJ()) {
					toAcrossChannelSearch();
				} else {
					if (Function.function.get("OttInfor")) {
						// 启动ott信息
						toNetResource();
					} else {
						Toast.makeText(
								context,
								getString(R.string.the_pro_is_not_Television_poly),
								1).show();
					}

				}

			}
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean hasProgram() {
		return programList != null && programList.size() > 0;
	}

	private void toNetResource() {
		Intent intent = new Intent();
		intent.setClass(context, OTTInfoActivity.class);
		intent.putExtra("PRO_NAME", programList.get(position).getPn());
		intent.putExtra("PRO_TYPE", programList.get(position).getPtype());
		intent.putExtra("PRO_EPISODE", programList.get(position).getJs());
		intent.putExtra("StartActivity", "ProgramListActivity");
		startActivity(intent);
	}

	private void toAcrossChannelSearch() {
		Intent intent = new Intent();
		intent.setClass(context, AcrossChannelSearchActivity.class);
		intent.putExtra("PRO_NAME", programList.get(position).getPn());
		intent.putExtra("PRO_ID", programList.get(position).getPid());
		intent.putExtra("PRO_TYPE", programList.get(position).getPtype());
		intent.putExtra("PRO_EPISODE", programList.get(position).getJs());
		startActivity(intent);
	}

	/**
	 * 过滤电视剧,于此同时也判断了节目是否存在
	 * 
	 * @return
	 */
	private boolean filterDSJ() {
		boolean isDSJ = false;
		String proTypes = "";
		proTypes = programList.get(position).getPtype();
		if (proTypes.trim().length() > 0) {
			String[] proType = proTypes.split(",");
			for (int typeCount = 0; typeCount < proType.length; typeCount++) {
				if (proType[typeCount].equals(itemType)) {
					isDSJ = true;
					break;
				}
			}
		}
		return isDSJ;
	}

}
